import React, { useEffect, useState } from 'react';
import {
    Card,
    Checkbox,
    Dialog,
    DialogProps, FormProps,
    MessagePlugin,
    Radio,
    Textarea,
    Switch,
    Tooltip,
    Link,
    PrimaryTable,
    Pagination,
    Message,

} from 'tdesign-react';
import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon } from 'tdesign-icons-react';
import moment from 'moment';
import { DownloadOutlined } from '@ant-design/icons';

import * as XLSX from 'xlsx';

import axios from 'axios';
import { flushSync } from 'react-dom';

import {
    Button,
    Cascader,
    DatePicker,
    Form,
    Input,
    InputNumber,
    Mentions,
    Select,
    TreeSelect,
    Segmented,
    Space,
    Table,
    Tag,
    Modal,
    Tabs,
    Menu,
} from 'antd';

import type { PaginationProps, TableProps } from 'antd';

import { message } from 'antd';
import TabPane from 'antd/es/tabs/TabPane';
import Sider from 'antd/es/layout/Sider';
axios.defaults.baseURL = 'http://127.0.0.1:3000/zlq'


export default function Log_on() {
    const [form] = Form.useForm()

    const [visible, setVisible] = useState(false);
    // const name = Form.useWatch('name', form);
    const gender = Form.useWatch('gender', form);
    // console.log('name', name);
    console.log('gender', gender);


    const [id, setId] = useState('')
    const [name, setName] = useState('')
    const [login, setLogin] = useState('')
    const [ip, setIp] = useState('')
    const [mac, setMac] = useState('')

    const getDictionary_cate = async () => {
        let { data: { code, dictionary_cateList } } = await axios.get(`/dictionary_cateList?name=${dictionary_cateName}`)
        if (code == 200) {
            setDictionary_data(dictionary_cateList)
        }
    }

    let [so_name, setSo_Name] = useState('')
    let [so_time, setSoTime] = useState('')

    const getLogOnList = async () => {
        // 检查 so_time 是否存在，并且是有效的时间格式
        let { data: { code, log_on_List, total } } = await axios.get(`/log_on_List`, {
            params: {
                page: page,
                pagesize: pageSize,
                name: so_name,
                time: so_time ? so_time : ''  // 如果 so_time 有值，传递它，否则传递空字符串
            }
        });

        if (code === 200) {
            setTotal(total);
            setData(log_on_List);
        }
    };

    let page = 1
    let pageSize = 5
    let [total, setTotal] = useState(0)

    const onChange: PaginationProps['onChange'] = (pageInfo) => {
        page = pageInfo.current
        pageSize = pageInfo.pageSize
        getLogOnList()
        console.log(pageInfo);
    };
    const onPageSizeChange: PaginationProps['onPageSizeChange'] = (size) => {
        pageSize = size
        getLogOnList()
        console.log('page-size:', size);
    };
    const onCurrentChange: PaginationProps['onCurrentChange'] = (index, pageInfo) => {
        page = index
        getLogOnList()
        console.log(`转到第${index}页`);
        console.log(pageInfo);
    };

    interface DataType {
        key: string;
        name: string;
        num: number;
        address: string;
        tags: string[];
    }

    //词条表格
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            render: (_, __, index) => <a>{index + 1}</a>,  // 使用行索引作为序号，index 从 0 开始，+1 让序号从 1 开始
        },
        {
            title: '登陆账号',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '更新时间',
            dataIndex: 'time',
            key: 'time',
            render: (text) => {
                // 通过 Date 对象来格式化时间
                const date = new Date(text);
                const formattedDate = date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                });
                return formattedDate; // 返回格式化后的日期字符串
            },
        },
        {
            title: '登录终端',
            dataIndex: 'login',
            key: 'login',
        },
        {
            title: '登录IP',
            dataIndex: 'ip',
            key: 'ip',
        }, {
            title: 'MAC地址',
            dataIndex: 'mac',
            key: 'mac',
        },
    ];

    const [data, setData] = useState<DataType[]>([]);

    //词条回显
    useEffect(() => {
        form.setFieldsValue({
            login: login,
            mac: mac,
            ip: ip,
            name: name,
        });
    }, [name, login, mac, ip,]);

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    //新增词条弹框
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        setId('')
        setIp("")
        setLogin("")
        setMac("")
        setName('')
        handleOk()
        setIsModalOpen(false);
    };

    const [dictionary_cateName, setDictionary_cateName] = useState('')

    const getSo = () => {
        getLogOnList();
    };

    // 导出为 Excel 的函数
    const exportToExcel = () => {
        // 数据转换
        const dataForExport = data.map((item, index) => ({
            序号: index + 1,
            登陆账号: item.name,
            更新时间: new Date(item.time).toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
            }),
            登录终端: item.login,
            登录IP: item.ip,
            MAC地址: item.mac,
        }));

        // 使用 xlsx 库生成 Excel 文件
        const ws = XLSX.utils.json_to_sheet(dataForExport);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '登录数据');

        // 导出 Excel 文件
        XLSX.writeFile(wb, '登录日志.xlsx');
    };


    useEffect(() => {
        getDictionary_cate()
        getLogOnList()
    }, [])
    return (
        <div>
            <div style={{ marginRight: "20px", }}>
                <Card bordered style={{ width: "1000px", marginBottom: "10px" }}>
                    <div style={{ display: 'flex' }}>
                        <Form.Item label="登录账号" name="so_name" initialValue={so_name} style={{ marginRight: "10px" }}>
                            <Input
                                value={so_name}
                                onChange={(e) => setSo_Name(e.target.value)}  // 更新输入框的值
                            />
                        </Form.Item>
                        <Form.Item label="登录时间" name="so_can_num" initialValue={so_time ? moment(so_time) : null} style={{ marginRight: "10px" }}>
                            <DatePicker
                                value={so_time ? moment(so_time) : null}  // 如果 so_time 存在，则转换为 moment 对象
                                onChange={(date, dateString) => setSoTime(dateString)}  // 更新日期值
                                style={{ width: '100%' }}
                                format="YYYY-MM-DD"  // 自定义日期格式
                            />
                        </Form.Item>
                        <Button style={{ marginLeft: "50px" }} type="primary" htmlType="submit" onClick={() => { getSo() }}>
                            搜索
                        </Button>
                    </div>
                </Card>
            </div>

            <div style={{ height: "500px" }}>
                <Card
                    bordered
                    headerBordered
                    style={{ height: "600px", width: "1000px" }}
                >
                    <div style={{ marginBottom: "50px" }}>
                        <Button style={{ float: "right" }} icon={<DownloadOutlined />} onClick={exportToExcel} type="primary"></Button>
                    </div>



                    <div>
                        <Table<DataType> pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data} />
                    </div>
                    <Pagination
                        total={total}
                        defaultPageSize={pageSize}
                        onChange={onChange}
                        onCurrentChange={onCurrentChange}
                        onPageSizeChange={onPageSizeChange}
                    />
                </Card>
            </div >
        </div >
    );
}